<template>
  <span v-loading="loading" class=" ">
    <el-button type="primary" plain :icon="CreditCard" @click="update_container_renew()">续费</el-button>
    <el-button type="success" plain :icon="CircleCheck" @click="sendSet('start')">启动</el-button>
    <el-button type="info" plain :icon="SwitchButton" @click="sendSet('stop')">关机</el-button>
    <el-button type="warning" plain :icon="Refresh" @click="sendSet('reboot')">重启</el-button>
    <el-button type="warning" plain :icon="Refresh" @click="toRein">重装</el-button>
    <!-- <el-button type="danger" plain :icon="Delete" @click="back_dialog = true">退款</el-button> -->
    <el-button :disabled="props.state != 2" type="primary" @click="SetConsole">
      控制台
    </el-button>
    <el-button type="success" :loading="rescueBut" @click="rescue">进入救援系统</el-button>
    <el-button :loading="rescue_exit_but" @click="rescue_exit">退出救援系统</el-button>
    <!-- <el-button @click="file()"> 文件管理 </el-button>
    <FileManage ref="childRef" /> -->
  </span>
  <el-dialog v-model="continueC" title="续费">
    <el-form :model="paylist" label-width="100px">
      <el-form-item label="续费时长/月">
        <el-input v-model="paylist.pay_months" type="number" min="0" style="width: 300px" />
      </el-form-item>
      <el-form-item label="支付方式">
        <el-checkbox label="优先使用余额支付" checked disabled />
        <el-radio v-model="paylist.pay_type" :value="0" size="large">支付宝
        </el-radio>
        <el-radio v-model="paylist.pay_type" :value="1" size="large">微信</el-radio>
      </el-form-item>
      <el-form-item v-if="pay_src != ''" label="扫码支付">
        <el-image style="width: 100px; height: 100px" :src="pay_src" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="pay_money">
        <el-statistic title="总计结算金额：" :value="payprice != 0 ? payprice + '元' : '- -' + ' 元'" suffix="">
          <template #suffix>
            <el-icon style="vertical-align: -20px">
              <ChatLineRound />
            </el-icon>
          </template>
        </el-statistic>
      </div>
      <div class="dialog-footer">
        <el-button @click="continueC = false">关闭</el-button>
        <el-button type="primary" :disabled="payprice == 0 ? true : false" @click="topay">提交订单
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="pay_dialog" title="支付" style="width: 90%; height: 1000px">
    <iframe :srcdoc="pay_url" frameborder="0" style="width: 100%; height: 800px" />
  </el-dialog>
  <!-- <el-dialog v-model="back_dialog" title="退款" width="40%">
    <el-form v-loading="loading">
      <el-form-item label="请先输入账号密码">
        <el-input v-model="pay_password" type="password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="back_dialog = false">关闭</el-button>
        <el-button type="primary" @click="toback">确认</el-button>
      </div>
    </template>
  </el-dialog> -->
  <el-dialog v-model="image_dialog" title="重装" width="40%">
    <el-form v-loading="loading">
      <el-form-item label="镜像">
        <el-select v-model="image_id" placeholder="你可以选择重装镜像">
          <el-option v-for="item in image_list" :key="item.value" :label="item.show_name ? item.show_name : item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="image_dialog = false">关闭</el-button>
        <el-button type="primary" @click="torein">确认重装</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  Refresh,
  SwitchButton,
  CircleCheck,
  Delete,
  CreditCard
} from "@element-plus/icons-vue";
import {
  start_vm,
  stop_vm,
  restart_vm,
  rescue_vm,
  unrescue_vm,
  get_vm_console,
  startAdminContainer,
  pay_request,
  procedureUpdateContainerRenew,
  backUserContainer,
  reinVmContainer
} from "@/api/user";
import { getUserMirrorList } from "@/api/mirror";
import {
  ref,
  getCurrentInstance,
  defineEmits,
  reactive,
  watch,
  onMounted
} from "vue";
import { message } from "@/utils/message";
import { useRouter } from "vue-router";
import FileManage from "@/views/self/components/FileManage.vue";
import { ElLoading } from "element-plus";
const router = useRouter();
const emits = defineEmits(["statusUpdated", "UpdataInfo"]);
onMounted(() => {
  console.log(props.pay, "价格");
});
const props = defineProps({
  id: [String, Number],
  console_url: [String],
  server_id: [String],
  trade_type: [String],
  pay: [String],
  state: [String]
});

const loading = ref(false);
// const childRef = ref();

const continueC = ref(false);
const pay_src = ref("");
const pay_url = ref("");
const pay_dialog = ref(false);

const paylist = reactive({
  pay_type: "0",
  pay_months: "1",
  instance_id: ""
});
const back_dialog = ref(false);
const pay_password = ref("");

const payprice = ref(0);
watch([paylist], () => {
  console.log(paylist.pay_months);
  getprice();
});
const getprice = () => {
  payprice.value = props.pay * paylist.pay_months;
};
//获取容器价格

// 文件管理
// const file = () => {
//   childRef.value.outer();
// };

// 虚拟机操作
const sendSet = async type => {
  loading.value = true;
  const handleResponse = res => {
    if (res.data.code === 200) {
      message(res.data.data, { type: "success" });
    } else {
      message(res.data.data, { type: "error" });
    }
    emits("statusUpdated");
    loading.value = false;
  };
  try {
    let res;
    if (type === "start") {
      res = await start_vm(props.id);
    } else if (type === "stop") {
      res = await stop_vm(props.id);
    } else if (type === "reboot") {
      res = await restart_vm(props.id);
    }
    handleResponse(res);
  } catch (error) {
    message("请求失败", { type: "error" });
    loading.value = false;
  }
};

// 链接控制台
const SetConsole = async () => {
  console.log("控制台");
  await get_vm_console(props.id).then(res => {
    if (res.data.code == 200) {
      window.open(res.data.data);
    }else{
      message(res.data.data, { type: "error" });
    }
  });
};
// 进入救援系统
const rescueBut = ref(false);
const rescue = async () => {
  rescueBut.value = true;
  await rescue_vm(props.id).then(res => {
    if (res.data.code == 200) {
      message(res.data.data, { type: "success" });
    } else {
      message(res.data.data.msg, { type: "error" });
    }
    rescueBut.value = false;
  });
};
// 退出救援系统
const rescue_exit_but = ref(false);
const rescue_exit = async () => {
  rescue_exit_but.value = true;
  await unrescue_vm(props.id).then(res => {
    if (res.data.code == 200) {
      message(res.data.data, { type: "success" });
    } else {
      message(res.data.data.msg, { type: "error" });
    }
    rescue_exit_but.value = false;
  });
};
function sendAdminSet(type = "start") {
  // loading.value = true;
  startAdminContainer(type, props.id)
    .then(res => {
      if (res.data.code === 200) {
        message("操作成功", {
          type: "success"
        });
      } else {
        message(res.data.data, {
          type: "success"
        });
      }
      loading.value = false;
    })
    .catch(e => {
      message(e.response.data.description, {
        type: "error"
      });
      loading.value = false;
    });
}
let { proxy } = getCurrentInstance();
const update_container_renew = () => {
  paylist.instance_id = props.id;
  continueC.value = true;
};
const topay = () => {
  paylist.trade_type = props.trade_type;
  procedureUpdateContainerRenew(paylist).then(res => {
    console.log("提交订单", res);
    if (res.data.code == 200) {
      //生成订单
      pay_request({
        pay_type: res.data.data.pay_type,
        trade_id: res.data.data.trade_id
      }).then(res => {
        if (res.data.data.type == "html") {
          pay_url.value = res.data.data.html;
          pay_dialog.value = true;
        } else if (res.data.data.type == "img") {
          pay_src.value = res.data.data.img;
        } else {
          message("支付成功", { type: "success" });
          continueC.value = false;
          emits("UpdataInfo");
        }
      });
    } else {
      message(res.data.msg, { type: "error" });
    }
  });
};
//退款
// const toback = () => {
//   if (pay_password.value == "") {
//     message("请输入密码", { type: "error" });
//   } else {
//     loading.value = true;
//     backUserContainer({
//       instance_id: props.id,
//       password: pay_password.value
//     }).then(res => {
//       if (res.data.code == 200) {
//         message("退款成功", { type: "success" });
//         back_dialog.value = false;
//         router.push("/product/product");
//       } else {
//         message(res.data.msg, { type: "error" });
//         loading.value = false;
//       }
//     });
//   }
// };
//重装
const image_dialog = ref(false);
const image_list = ref([]);
const image_id = ref();
const toRein = async () => {
  image_dialog.value = true;
  let res = await getUserMirrorList({
    server_id: props.server_id,
    count: 100,
    key: "",
    page: 1
  });
  console.log("获取镜像", res.data.data);
  res = res.data.data;
  image_list.value = res.map(item => {
    return {
      label: item.name,
      value: item.id,
      show_name: item.show_name
    };
  });
};
const torein = () => {
  const loading = ElLoading.service({
    lock: true,
    text: "容器重装中..."
  });

  reinVmContainer(props.id, { image_id: image_id.value })
    .then(res => {
      console.log(res);
      if (res.data.code == 200) {
        message(res.data.data, { type: "success" });
        loading.close();
        image_dialog.value = false;
      } else {
        message(res.data.msg, { type: "error" });
        loading.close();
      }
    })
    .catch(e => {
      console.log(e);
      message("重装失败", { type: "error" });
      loading.close();
    });
};
</script>

<style lang="scss" scoped></style>
